package com.patternbox.eclipse.model;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Scanner;
import java.util.Set;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.part.FileEditorInput;

/**
 * Pool of all available design pattern instances.
 * Use: First set up a lookup folder (setLookUpFolder())
 * Note: Needs a "lookupfolder" in every project in the workspace
 */

public class DesignPatternInstancePool {
	
	private static String sLookUpFolder = "Patterns";
	
	private static ArrayList<DesignPatternInstance> sPatterns;
	
	
	/**
	 * Initialize design pattern instance pool
	 */
	public static void initialize() {
		try {			
			 sPatterns = new ArrayList<DesignPatternInstance>();
			// Filtra todos los .xdp del workspace 
			IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
			IProject[] projects = workspaceRoot.getProjects();
			ArrayList<IFolder> folders = new ArrayList<IFolder>();
			for (IProject p : projects) {
				IFolder f = p.getFolder(sLookUpFolder);
				if (f != null) folders.add(f);
			}
			ArrayList<IFile> workspaceFiles = new ArrayList<IFile>();
			for (IFolder f : folders) {
				if (f.exists()) {
					for (IResource r : f.members()) {
						if (r.getType() == IResource.FILE && r.getFileExtension().equals("xdp")){
							workspaceFiles.add((IFile)r);
						}
					}
				}
			}
			
			// Crea los modelos de instancias de patrones con los .xdp encontrados
			for (IFile f : workspaceFiles) {
				sPatterns.add(new DesignPatternInstance(new FileEditorInput(f)));
			}
			
		} catch (CoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void setLookUpFolder(String lookUpFolder) {
		sLookUpFolder = lookUpFolder;
	}
	
	/**
	 * 
	 * @return All instances of patterns found inside the workspace.
	 */
	public static ArrayList<DesignPatternInstance> getInstances() {
		return sPatterns;
	}
	
	/**
	 * 
	 * @param pattern Design Pattern's name to be found.
	 * @return Filtered array of pattern instances
	 */
	public static ArrayList<DesignPatternInstance> getIntances(String pattern) {
		ArrayList<DesignPatternInstance> instances = new ArrayList<DesignPatternInstance>();
		for (DesignPatternInstance d : sPatterns) {
			if (d.getDesignPatternName().equals(pattern))
				instances.add(d);
		}
		return instances;
	}

}
